using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using ECommerce.Library.DataStructure;
using AutoGear.BLL;
using System.Collections.Generic;
using ECommerce.Library.Web;
using ECommerce.Library;

public partial class controls_wucSpecialList : BaseControl
{
    private int _currentPageIndex;
    private int _pageSize;
    private int _totalPages;
    private string _sortOder;

    private string _categoryName;
    public string CategoryName
    {
        get { return this._categoryName; }
        set { this._categoryName = value; }
    }


    private string _searchProductName;
    public string SearchProductName
    {
        get { return this._searchProductName; }
        set { this._searchProductName = value; }
    }

    private string _searchItemNumber;
    public string SearchItemNumber
    {
        get { return this._searchItemNumber; }
        set { this._searchItemNumber = value; }
    }

    private int _repeatColumns = 3;
    public int RepeatedColumns
    {
        get { return this._repeatColumns; }
    }

    private int _categoryId;
    public int CategoryId
    {
        get { return this._categoryId; }
        set { this._categoryId = value; }
    }

    private int _manufacturerId;
    public int ManufacturerId
    {
        get { return this._manufacturerId; }
        set { this._manufacturerId = value; }
    }

    private void ReadPagingData()
    {
        this._currentPageIndex = Convert.ToInt32(ViewState["CurrentPageIndex"]);
        this._pageSize = Convert.ToInt32(ViewState["PageSize"]);
        this._totalPages = Convert.ToInt32(ViewState["TotalPages"]);
        this._sortOder = Convert.ToString(ViewState["SortOrder"]);
        this._searchItemNumber = Convert.ToString(ViewState["SearchItemNumber"]);
        this._searchProductName = Convert.ToString(ViewState["SearchProductName"]);
        this._manufacturerId = Convert.ToInt32(ViewState["ManufacturerId"]);
        this._categoryId = Convert.ToInt32(ViewState["CategoryId"]);
    }

    private void WritePagingData()
    {
        ViewState["CurrentPageIndex"] = this._currentPageIndex;
        ViewState["PageSize"] = this._pageSize;
        ViewState["TotalPages"] = this._totalPages;
        ViewState["SortOrder"] = this._sortOder;
        ViewState["SearchItemNumber"] = this._searchItemNumber;
        ViewState["SearchProductName"] = this._searchProductName;
        ViewState["ManufacturerId"] = this._manufacturerId;
        ViewState["CategoryId"] = this._categoryId;
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            if (!IsPostBack)
            {
                //default parameter
                if ((!string.IsNullOrEmpty(Request.QueryString["view"])) && (Request.QueryString["view"] == "all"))
                {
                    this._pageSize = 99999;
                }
                else
                {
                    this._pageSize = 12;
                }
                this._currentPageIndex = 1;
                InitState();
                LoadRepeaterItems();
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
    private void InitState()
    {
        this._pageSize = int.Parse("12");
        this._currentPageIndex = 1;
        this._sortOder = "Default";
        this._searchItemNumber = AutoGearSessionManager.SearchItemNumber;
        this._searchProductName = AutoGearSessionManager.SearchKeyword;
    }

    protected void LoadRepeaterItems()
    {
        ReadWriteCustomCollection<Product> specialProduct = Product.GetProductListSpecials(); ;
        ReadWriteCustomCollection<Product> specialProductCount = Product.SpecialProducts(this._currentPageIndex, this._pageSize, DataState.Active);
        //if (this._currentPageIndex >1)
        //{
        //    specialProduct = Product.Products(this._currentPageIndex, this._pageSize, DataState.Active);
        //}
        //else
        //{
        //   specialProduct = Product.GetProductListSpecials();
        //}
        ReadWriteCustomCollection<Product> tempSpecialProduct;
        List<ReadWriteCustomCollection<Product>> list = new List<ReadWriteCustomCollection<Product>>();
        tempSpecialProduct = new ReadWriteCustomCollection<Product>();
        int count = 0;
        if (specialProduct != null)
        {
            foreach (Product product in specialProductCount)
            {
                tempSpecialProduct.Add(product);
                count++;
                if (count % RepeatedColumns == 0)
                {
                    list.Add(tempSpecialProduct);
                    tempSpecialProduct = new ReadWriteCustomCollection<Product>();
                }
            }
            if (tempSpecialProduct.Count > 0)
            {
                list.Add(tempSpecialProduct);
            }
            rptVertical.DataSource = list;
            rptVertical.DataBind();
        }
        this._totalPages = (int)Math.Ceiling(specialProduct.Count / (double)this._pageSize);

        if (this._totalPages > 10)
        {
            this._totalPages = 10;
        }

        int firstItem = (this._currentPageIndex - 1) * this._pageSize;
        int lastItem = this._currentPageIndex * this._pageSize - 1;

        if (lastItem >= count)
            lastItem = count - 1;
        WritePagingData();
        BindPager();
        if (specialProduct.Count > count)
        {
            lkbNext.Visible = true;
            lkbNextBottom.Visible = true;
            if (this._currentPageIndex > 1)
            {
                lkbPrev.Visible = true;
                lkbPrevBottom.Visible = true;
            }
        }
    }
    protected void Vertical_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        try
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                Repeater rptHorizontal = (Repeater)e.Item.FindControl("rptHorizontal");
                rptHorizontal.DataSource = (ReadWriteCustomCollection<Product>)e.Item.DataItem;
                rptHorizontal.DataBind();
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    protected void Horizontal_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        try
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                Product product = (Product)e.Item.DataItem;

                HyperLink hlkProductNameLink = (HyperLink)e.Item.FindControl("hlkProductNameLink");
                hlkProductNameLink.Text = product.ProductName;
                hlkProductNameLink.NavigateUrl = product.ProductUrl;

                Label lblProductName2 = (Label)e.Item.FindControl("lblProductName2");
                lblProductName2.Text = product.ProductName2;

                HyperLink hlkProductPictureLink = (HyperLink)e.Item.FindControl("hlkProductPictureLink");
                hlkProductPictureLink.NavigateUrl = product.ProductUrl;


                //Image imgSpecial = (Image)e.Item.FindControl("imgSpecial");
                //imgSpecial.Visible = product.IsSpecial;

                Image imgProductImage = (Image)e.Item.FindControl("imgProductImage");
                System.Drawing.Size originalImageDimension = ImageResizer.GetImageDimension(product.ProductImageSmallThumbnail);
                if (originalImageDimension.Width > 150)
                {
                    imgProductImage.Style.Add("width", "150px;");
                }
                imgProductImage.ImageUrl = ImageResizer.CheckImageMissing(product.ProductImageSmallThumbnail, AutoGear.BLL.SiteSettings.NoImageSmallThumbnailUrl);
                imgProductImage.AlternateText = product.ProductName;
                if (imgProductImage.ImageUrl == AutoGear.BLL.SiteSettings.NoImageUrl)
                {
                    Panel pnlImagePanle = (Panel)e.Item.FindControl("pnlImagePanle");
                    if (pnlImagePanle != null)
                    {
                        pnlImagePanle.Visible = false;
                    }
                }
                Label lblquickPrice = (Label)e.Item.FindControl("lblquickPrice");
                Label lblPrice = (Label)e.Item.FindControl("lblPrice");
                lblPrice.Text = ECommerce.Library.ECommerce.Utility.FormatPriceText(product.ProductPrice);
                if (product.StandardCost > 0)
                {
                    Label lblSalePrice = (Label)e.Item.FindControl("lblSalePrice");
                    lblSalePrice.Text = ECommerce.Library.ECommerce.Utility.FormatPriceText(product.StandardCost);
                    lblquickPrice.Text = ECommerce.Library.ECommerce.Utility.FormatPriceText(product.StandardCost);
                }
                else
                {
                    lblPrice.CssClass = "product-list-item-price2";
                    lblquickPrice.Text = ECommerce.Library.ECommerce.Utility.FormatPriceText(product.ProductPrice);
                }
                //Label lblSalePrice = (Label)e.Item.FindControl("lblSalePrice");
                //lblSalePrice.Text = ECommerce.Library.ECommerce.Utility.FormatPriceText(product.StandardCost);

                HyperLink hlkDetail = (HyperLink)e.Item.FindControl("hlkDetail");
                hlkDetail.NavigateUrl = product.ProductUrl;
                
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
    
    protected void rptHorizontal_ItemCommand(object sender, RepeaterCommandEventArgs e)
    {
        try
        {
            if (e.CommandName == "AddToCart")
            {
                int productId;
                if (int.TryParse(e.CommandArgument.ToString(), out productId))
                {
                    if (productId > 0)
                    {
                        TextBox tbxQuantity = (TextBox)e.Item.FindControl("tbxQuantity");
                        if (tbxQuantity != null)
                        {
                            int qty;
                            int.TryParse(tbxQuantity.Text.ToString().Trim(), out qty);
                            
                            Product product = Product.Load(productId);
                            if (qty > 0)
                            {
                                this.AddCartItemToShoppingCart(qty, product, "", "N");
                                uccResponseMessage.SetSuccessMessage(AutoGearCommonMessage.AddToCartSuccessful);
                                uccResponseMessage.Visible = true;

                            }
                            else
                            {
                                uccResponseMessage.SetFailMessage(AutoGearCommonMessage.AddToCartInvalidQuantity);
                                uccResponseMessage.Visible = true;
                            }
                        }

                    }
                }
            }
        }
        catch (Exception ex)
        {
            uccResponseMessage.SetFailMessage(AutoGearCommonMessage.AddToCartFailed);
            uccResponseMessage.Visible = true;
        }
    }
    protected void AddCartItemToShoppingCart(int qty, Product product, string MetalType, string GiftWrapper)
    {
        try
        {
            ShoppingCart shoppingcart = AutoGearSessionManager.ShoppingCart;
            CartItem cartItem = new CartItem(product, qty, MetalType, GiftWrapper);
            shoppingcart.AddCartItem(cartItem);
            AutoGearSessionManager.ShoppingCart = shoppingcart;

        }
        catch (Exception ex)
        {
        }
    }
    protected void rptSiteMap_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        try
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
                {
                    HyperLink hlkSiteMap = (HyperLink)e.Item.FindControl("hlkSiteMap");
                    KeyValuePair<string, string> node = (KeyValuePair<string, string>)e.Item.DataItem;
                    hlkSiteMap.NavigateUrl = node.Value;
                    hlkSiteMap.Text = node.Key.ToLower() == "none" ? "Home" : node.Key;
                }
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    protected void lnkSortByPrice_Click(object sender, EventArgs e)
    {
        ReadPagingData();
        if (this._sortOder == "By Price")
            this._sortOder = "By Price DESC";
        else
            this._sortOder = "By Price";
        WritePagingData();
        LoadRepeaterItems();
    }
    protected void lnkSortUp_Click(object sender, EventArgs e)
    {
        ReadPagingData();
        this._sortOder = "By Name";
        WritePagingData();
        LoadRepeaterItems();
    }
    protected void lnkSortDown_Click(object sender, ImageClickEventArgs e)
    {
        ReadPagingData();
        this._sortOder = "By Name DESC";
        WritePagingData();
        LoadRepeaterItems();
    }
    protected void PageSize_Changed(object sender, EventArgs e)
    {
        ReadPagingData();
        this._pageSize = int.Parse("12");
        WritePagingData();
        LoadRepeaterItems();
    }

    protected void SortOrder_Changed(object sender, EventArgs e)
    {
        ReadPagingData();
        this._sortOder = "Asc";
        WritePagingData();
        LoadRepeaterItems();
    }
    protected void rptPagingBottom_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        try
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                int pageIndex = (int)e.Item.DataItem;
                LinkButton lkbPageIndex = (LinkButton)e.Item.FindControl("lkbPageIndexBottom");
                if (_currentPageIndex == pageIndex)
                {
                    DisableLinkButtonStyle(lkbPageIndex);
                }
                else
                {
                    EnableLinkButtonStyle(lkbPageIndex);
                }
                lkbPageIndex.Text = pageIndex.ToString();
                lkbPageIndex.CommandArgument = pageIndex.ToString();
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
    protected void rptPagingBottom_ItemCommand(object source, RepeaterCommandEventArgs e)
    {
        try
        {
            LinkButton lkbPageIndex = (LinkButton)e.CommandSource;
            ReadPagingData();
            this._currentPageIndex = int.Parse(lkbPageIndex.CommandArgument);
            WritePagingData();
            LoadRepeaterItems();
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
    protected void rptPaging_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        try
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                int pageIndex = (int)e.Item.DataItem;
                LinkButton lkbPageIndex = (LinkButton)e.Item.FindControl("lkbPageIndex");
                if (_currentPageIndex == pageIndex)
                {
                    DisableLinkButtonStyle(lkbPageIndex);
                }
                else
                {
                    EnableLinkButtonStyle(lkbPageIndex);
                }
                lkbPageIndex.Text = pageIndex.ToString();
                lkbPageIndex.CommandArgument = pageIndex.ToString();
                
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
    protected void rptPaging_ItemCommand(object source, RepeaterCommandEventArgs e)
    {
        try
        {
            LinkButton lkbPageIndex = (LinkButton)e.CommandSource;
            ReadPagingData();
            this._currentPageIndex = int.Parse(lkbPageIndex.CommandArgument);
            WritePagingData();
            LoadRepeaterItems();
          
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
    protected void lkbPrev_Click(object sender, EventArgs e)
    {
        try
        {
            ReadPagingData();
            _currentPageIndex = _currentPageIndex > 1 ? _currentPageIndex - 1 : 1;
            WritePagingData();
            LoadRepeaterItems();
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
    protected void lkbNext_Click(object sender, EventArgs e)
    {
        try
        {
            ReadPagingData();
            _currentPageIndex = _currentPageIndex < this._totalPages ? _currentPageIndex + 1 : this._totalPages;
            WritePagingData();
            LoadRepeaterItems();
            if (_currentPageIndex > 1)
            {
                lkbPrev.Visible = true;
            }
            else
            {
                lkbPrev.Visible = false;
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
    protected void lkbPrevBottom_Click(object sender, EventArgs e)
    {
        try
        {
            ReadPagingData();
            _currentPageIndex = _currentPageIndex > 1 ? _currentPageIndex - 1 : 1;
            WritePagingData();
            LoadRepeaterItems();
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
    protected void lkbNextBottom_Click(object sender, EventArgs e)
    {
        try
        {
            ReadPagingData();
            _currentPageIndex = _currentPageIndex < this._totalPages ? _currentPageIndex + 1 : this._totalPages;
            WritePagingData();
            LoadRepeaterItems();
            if (_currentPageIndex > 1)
            {
                lkbPrevBottom.Visible = true;
            }
            else
            {
                lkbPrevBottom.Visible = false;
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
    protected void EnableLinkButtonStyle(LinkButton lkb)
    {
        lkb.CssClass = "paging-numbers";
        lkb.OnClientClick = "javascript:return true;";
    }

    protected void DisableLinkButtonStyle(LinkButton lkb)
    {

        lkb.CssClass = "paging-numbers current-page";
        lkb.OnClientClick = "javascript:return false;";
    }
    private void BindPager()
    {
        List<int> pagingList = new List<int>();

        lkbPrev.Visible = false;
        lkbNext.Visible = false;
        lkbPrevBottom.Visible = false;
        lkbNextBottom.Visible = false;

        for (int i = 0; i < this._totalPages; i++)
        {
            pagingList.Add(i + 1);
        }
        rptPaging.DataSource = pagingList;
        rptPaging.DataBind();

        rptPagingBottom.DataSource = pagingList;
        rptPagingBottom.DataBind();
    }

}
